package com.tao.springai.service;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class ChatHistoryService {

    // 简单地用内存存储聊天历史，实际应用中建议使用数据库
    private final Map<String, ChatSession> sessions = new ConcurrentHashMap<>();

    /**
     * 创建一个新的聊天会话
     * @param title 会话标题
     * @return 新会话的ID
     */
    public String createSession(String title) {
        String sessionId = UUID.randomUUID().toString();
        sessions.put(sessionId, new ChatSession(sessionId, title));
        System.out.println("Creating new session: " + sessionId + " with title: " + title);
        return sessionId;
    }

    /**
     * 添加消息到会话中
     * @param sessionId 会话ID
     * @param message 消息内容
     * @param isUser 是否为用户消息
     */
    public void addMessage(String sessionId, String message, boolean isUser) {
        ChatSession session = sessions.get(sessionId);
        if (session != null) {
            session.messages.add(new ChatMessage(
                    isUser ? "user" : "assistant",
                    message,
                    LocalDateTime.now()
            ));
            System.out.println("Added " + (isUser ? "user" : "assistant") + " message to session: " + sessionId);
        } else {
            System.out.println("Session not found: " + sessionId);
        }
    }

    /**
     * 获取会话中的所有消息
     * @param sessionId 会话ID
     * @return 消息列表
     */
    public List<ChatMessage> getMessages(String sessionId) {
        ChatSession session = sessions.get(sessionId);
        List<ChatMessage> messages = session != null ? new ArrayList<>(session.messages) : new ArrayList<>();
        System.out.println("Retrieved " + messages.size() + " messages from session: " + sessionId);
        return messages;
    }

    /**
     * 更新会话标题
     * @param sessionId 会话ID
     * @param title 新标题
     * @return 是否更新成功
     */
    public boolean updateSessionTitle(String sessionId, String title) {
        ChatSession session = sessions.get(sessionId);
        if (session != null) {
            session.title = title;
            System.out.println("Updated session title: " + sessionId + " to: " + title);
            return true;
        }
        System.out.println("Session not found for title update: " + sessionId);
        return false;
    }

    /**
     * 获取本周的聊天会话
     * @return 本周会话列表
     */
    public List<ChatSessionDTO> getRecentSessions() {
        LocalDateTime oneWeekAgo = LocalDateTime.now().minus(7, ChronoUnit.DAYS);
        List<ChatSessionDTO> result = sessions.values().stream()
                .filter(s -> s.createdAt.isAfter(oneWeekAgo))
                .map(s -> new ChatSessionDTO(s.id, s.title, Date.from(s.createdAt.atZone(ZoneId.systemDefault()).toInstant())))
                .sorted(Comparator.comparing(ChatSessionDTO::getCreatedAt).reversed())
                .collect(Collectors.toList());
        
        System.out.println("Retrieved " + result.size() + " recent sessions");
        return result;
    }

    /**
     * 获取更早的聊天会话
     * @return 本周之前的会话列表
     */
    public List<ChatSessionDTO> getOlderSessions() {
        LocalDateTime oneWeekAgo = LocalDateTime.now().minus(7, ChronoUnit.DAYS);
        List<ChatSessionDTO> result = sessions.values().stream()
                .filter(s -> s.createdAt.isBefore(oneWeekAgo))
                .map(s -> new ChatSessionDTO(s.id, s.title, Date.from(s.createdAt.atZone(ZoneId.systemDefault()).toInstant())))
                .sorted(Comparator.comparing(ChatSessionDTO::getCreatedAt).reversed())
                .collect(Collectors.toList());
        
        System.out.println("Retrieved " + result.size() + " older sessions");
        return result;
    }

    /**
     * 聊天会话类
     */
    private static class ChatSession {
        private final String id;
        private String title;
        private final List<ChatMessage> messages = new ArrayList<>();
        private final LocalDateTime createdAt;

        public ChatSession(String id, String title) {
            this.id = id;
            this.title = title;
            this.createdAt = LocalDateTime.now();
        }
    }

    /**
     * 聊天消息类
     */
    public static class ChatMessage {
        private final String role;
        private final String content;
        private final LocalDateTime timestamp;

        public ChatMessage(String role, String content, LocalDateTime timestamp) {
            this.role = role;
            this.content = content;
            this.timestamp = timestamp;
        }

        public String getRole() {
            return role;
        }

        public String getContent() {
            return content;
        }

        public LocalDateTime getTimestamp() {
            return timestamp;
        }
    }

    /**
     * 聊天会话DTO，用于返回给前端
     */
    public static class ChatSessionDTO {
        private final String id;
        private final String title;
        private final Date createdAt;

        public ChatSessionDTO(String id, String title, Date createdAt) {
            this.id = id;
            this.title = title;
            this.createdAt = createdAt;
        }

        public String getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        public Date getCreatedAt() {
            return createdAt;
        }
    }
} 